local Msg = require("core.Msg")
local OnlineConfig = require("excel.Fuli").online
local FuliDefine = require("fuli.FuliDefine")
local Grid = require("bag.Grid")
local BagLogic = require("bag.BagLogic")
local Broadcast = require("broadcast.Broadcast")
local Lang = require("common.Lang")
local Handler = require("fuli.HandlerL")
local Log = require("common.Log")

--检查是否可领取奖励
function checkShowTips(human)
  for i=1, #OnlineConfig do
    if human.db.fuliIsGet[FuliDefine.FULI_TYPE_ONLINE * 15 + i - 1] == FuliDefine.REWARD_CAN_GET then
      return 1
    end
  end
  return 0
end

function getRewardList(human)
  changeStatus(human)
  local sendMsg = Msg.gc.GC_FULI_REWARD
  local cache = {}
  sendMsg.list[0] = #OnlineConfig
  for i=1, #OnlineConfig do
    sendMsg.list[i].page = FuliDefine.FULI_TYPE_ONLINE
    sendMsg.list[i].canGet = human.db.fuliIsGet[FuliDefine.FULI_TYPE_ONLINE * 15 + i - 1]
    sendMsg.list[i].vipCanGet = 0
    sendMsg.list[i].condition = OnlineConfig[i].time
    sendMsg.list[i].needYuanbao = 0
    sendMsg.list[i].reward[0] = #OnlineConfig[i].reward
    for j=1, #OnlineConfig[i].reward do
      Grid.create(cache, OnlineConfig[i].reward[j][1], OnlineConfig[i].reward[j][2])
      Grid.makeItem(cache, sendMsg.list[i].reward[j], 0, human)
    end    
    sendMsg.list[i].vipReward[0] = 0 
    sendMsg.list[i].onlineTime = human.db.onLineSeconds
    sendMsg.list[i].percent = 0
  end
  Msg.send(sendMsg, human.fd)  
end

function changeStatus(human)
  for i=1, #OnlineConfig do
    if human.db.onLineSeconds >= OnlineConfig[i].time and 
      human.db.fuliIsGet[FuliDefine.FULI_TYPE_ONLINE * 15 + i - 1] == FuliDefine.REWARD_NOT_CAN_GET then
      human.db.fuliIsGet[FuliDefine.FULI_TYPE_ONLINE * 15 + i - 1] = FuliDefine.REWARD_CAN_GET
    end
  end
end

function getIndex(human, condition)
  for i=1, #OnlineConfig do
    if OnlineConfig[i].time == condition then
      return i
    end
  end
  return 0
end

function getReward(human, condition)
  local index = getIndex(human, condition)
  if index == 0 then
    return
  end
    if human.db.fuliIsGet[FuliDefine.FULI_TYPE_ONLINE * 15 + index - 1] ~= FuliDefine.REWARD_CAN_GET then
    return
  end
  if not BagLogic.checkCanAddItemList(human, OnlineConfig[index].reward, #OnlineConfig[index].reward) then
    return Broadcast.sendBroadcast(human, Lang.DOWN, Lang.FULI_BAG_NOT_ENOUGH)
  end
  human.db.fuliIsGet[FuliDefine.FULI_TYPE_ONLINE * 15 + index - 1] = FuliDefine.REWARD_ALREADY_GET
  for i=1, #OnlineConfig[index].reward do
    BagLogic.addItem(human, OnlineConfig[index].reward[i][1], 1, OnlineConfig[index].reward[i][2], "fulidating")
  end
  getRewardList(human)
  Handler.checkShowTips(human)
  Log.write(Log.LOGID_OSS_ONLINE_REWARD, human._id, human.account, human.name,human.db.lv, condition)
end

function updateStatus(human)
  for i=1, #OnlineConfig do
    human.db.fuliIsGet[FuliDefine.FULI_TYPE_ONLINE * 15 + i - 1] = FuliDefine.REWARD_NOT_CAN_GET
  end
end
